import axios from 'axios';
import environment from '@/environment';
import $storage from '@/services/storage.service';
import { defer, Observable, map, of, delay, catchError } from 'rxjs';

class Http {
  get(config) {
    return this.buildRequest({ ...config, method: 'GET' });
  }

  post(config) {
    return this.buildRequest({ ...config, method: 'POST' });
  }

  buildJwtHeaders(ticket) {
    return { "Authorization": `Bearer ${ticket}` };
  }

  buildHeaders(config) {
    let jwtHeaders = $storage.getUserTicket() ? this.buildJwtHeaders($storage.getUserTicket()) : {};
    const mixedHeaders = { ...jwtHeaders, ...config.headers };
    return mixedHeaders;
  }

  buildUrl(config) {
    return config.url.startsWith('http')
      ? config.url
      : `${environment.apiDomain}${config.url}`;
  }

  buildResponse(config) {
    return (response) => {
      if (response.status < 200 || response.status > 299) {
        throw new Error('网络错误', response.status);
      }
      try {
        JSON.parse(JSON.stringify(response.data));
      } catch (error) {
        throw new Error('解析错误', 500);
      }

      let data = response.data;
      return { ...data, requestConfig: config };
    };
  }

  buildError(config) {
    return (error) => {
      return of({
        status: false,
        message: error.message || '网络错误',
        data: null,
        code: error?.code || 500,
        timestamp: Date.now(),
        requestConfig: config,
      });
    };
  }

  buildRequest(config) {
    return defer(() =>
      axios({
        ...config,
        url: this.buildUrl(config),
        headers: this.buildHeaders(config),
      })
    ).pipe(
      // delay(1000),
      map(this.buildResponse(config)),
      catchError(this.buildError(config)),
    );
  }

  searchSuggest(keyword) {
    return this.get({ url: `/kugo/search/suggest?keyword=${keyword}` });
  }

  updateSchedule(data) {
    return this.post({ url: `/api/schedule/update`, data });
  }

  getScheduleList() {
    return this.get({ url: `/api/schedule/list` });
  }
  deleteSchedule(id) {
    return this.post({ url: `/api/schedule/delete`, data: { id } });
  }

  updateRole(data) {
    return this.post({ url: `/api/role/update`, data });
  }

  getRoleList() {
    return this.get({ url: `/api/role/list` });
  }
  deleteRole(id) {
    return this.post({ url: `/api/role/delete`, data: { id } });
  }
  uploadRoleJson(data) {
    return this.post({ url: `/api/role/upload`, data, headers: { 'Content-Type': 'multipart/form-data' } });
  }
  clearRole() {
    return this.post({ url: `/api/role/clear` });
  }
  getLogs() {
    return this.get({ url: `/api/log/list` });
  }
  clearLogs() {
    return this.post({ url: `/api/log/clear` });
  }
  getCraftLog() {
    return this.get({ url: `/api/craft/get_log` });
  }

  getRoleScreenshot(path) {
    return this.get({ url: `/api/screenshot/get_screenshot?path=${path}` });
  }
}

const $http = new Http();

export default $http;

// export default $http;
